package dao.impl;
import dao.IUserDao;
import entity.User;

public class UserDaoImpl implements IUserDao{

	private User[] users;
	private User loginUser;
	
	public UserDaoImpl() {
		users = new User[10];
	}
	private int getUseFulIndex(){
		for (int i = 0; i < users.length; i++) {
			if(null == users[i]){
				return i;
			}
		}
		return -1;
	}
	@Override
	public boolean save(User user) {
		int index = this.getUseFulIndex();
		if(-1 == index){
			return false;
		}
		for (int i = 0; i < index ; i++) {
			if(users[i].getAccount().getId() == user.getAccount().getId()){
				return false;
			}
		}
		users[index] = user;
		return true;
	}

	@Override
	public boolean update(User user) {
		return false;
	}

	@Override
	public boolean delete(User user) {
		return false;
	}

	@Override
	public User selectById(int id) {
		return null;
	}

	@Override
	public User selectAll() {
		return null;
	}

	@Override
	public boolean regist(User user) {
		return this.save(user);
	}

	@Override
	public User login(User user) {
		int index = this.getUseFulIndex();
		for (int i = 0; i < index ; i++) {
			if(users[i].getAccount().getId() == user.getAccount().getId()
				&& users[i].getAccount().getPassword().equals(user.getAccount().getPassword())){
				loginUser = users[i];
				return loginUser;
			}
		}
		return null;
	}

	@Override
	public boolean saveMoney(double money) {
		double m = loginUser.getAccount().getMoney();
		if( money >=0 ){
			loginUser.getAccount().setMoney(m+money);
			return true;
		}
		return false;
	}

	@Override
	public boolean withDraw(double money) {
		double m = loginUser.getAccount().getMoney();
		if(m >= money && money >=0 ){
			loginUser.getAccount().setMoney(m-money);
			return true;
		}
		return false;
	}

	@Override
	public boolean transform(int id, double money) {
		int index = this.getUseFulIndex();
		User u = null;
		for (int i = 0; i < index; i++) {
			if(users[i].getAccount().getId() == id){
				u = users[i];
				break;
			}
		}
		double m = loginUser.getAccount().getMoney();
		if(u != null && m>=money && money >= 0){
			loginUser.getAccount().setMoney(m-money);
			u.getAccount().setMoney(u.getAccount().getMoney()+money);
			return true;
		}
		return false;
	}

	@Override
	public double checkBalance() {
		return loginUser.getAccount().getMoney();
	}

}
